<template>
  <div class="product-container">
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button type="primary" @click="goToAdd">添加商品</el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="商品名称"
            clearable
            @keyup.enter.native="handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.categoryId" placeholder="商品分类" clearable>
            <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="商品状态" clearable>
            <el-option :value="1" label="已上架"></el-option>
            <el-option :value="0" label="已下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品列表 -->
    <el-table
      :data="productList"
      border
      v-loading="loading"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        label="商品图片"
        width="120">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.image"
            fit="cover"
            :preview-src-list="[scope.row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="商品名称"
        min-width="200">
      </el-table-column>
      <el-table-column
        prop="categoryName"
        label="分类"
        width="120">
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        width="100">
        <template slot-scope="scope">
          ¥ {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column
        prop="stock"
        label="库存"
        width="100">
      </el-table-column>
      <el-table-column
        prop="sales"
        label="销量"
        width="100">
      </el-table-column>
      <el-table-column
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)">
          </el-switch>
          <div class="status-text">{{ scope.row.status === 1 ? '已上架' : '已下架' }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getProductList, deleteProduct, updateProductStatus } from '@/api/product';
import { getCategoryTree } from '@/api/category';

export default {
  name: 'ProductList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        keyword: '',
        categoryId: null,
        status: null
      },
      // 商品列表
      productList: [],
      // 分类列表
      categories: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 加载状态
      loading: false
    }
  },
  created() {
    this.fetchCategories();
    this.fetchProducts();
  },
  methods: {
    // 获取分类列表
    fetchCategories() {
      getCategoryTree()
        .then(res => {
          if (res.code === 200) {
            this.categories = this.flattenCategories(res.data || []);
          }
        })
        .catch(err => {
          console.error('获取分类失败', err);
          this.$message.error('获取分类失败');
        });
    },
    
    // 扁平化分类树
    flattenCategories(categories, result = []) {
      categories.forEach(category => {
        result.push(category);
        if (category.children && category.children.length > 0) {
          this.flattenCategories(category.children, result);
        }
      });
      return result;
    },
    
    // 获取商品列表
    fetchProducts() {
      this.loading = true;
      
      // 获取当前商家ID (实际项目中应从登录用户信息或全局状态中获取)
      const merchantId = 1; // 假设当前商家ID为1
      
      const params = {
        merchantId,
        page: this.currentPage,
        size: this.pageSize,
        ...this.searchForm
      };
      
      getProductList(params)
        .then(res => {
          if (res.code === 200) {
            this.productList = res.data.records || [];
            this.total = res.data.total || 0;
          } else {
            this.$message.error(res.message || '获取商品列表失败');
          }
        })
        .catch(err => {
          console.error('获取商品列表失败', err);
          this.$message.error('获取商品列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchProducts();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        keyword: '',
        categoryId: null,
        status: null
      };
      this.currentPage = 1;
      this.fetchProducts();
    },
    
    // 修改每页大小
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchProducts();
    },
    
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchProducts();
    },
    
    // 前往添加商品页面
    goToAdd() {
      this.$router.push('/merchant/product/add');
    },
    
    // 编辑商品
    handleEdit(row) {
      this.$router.push(`/merchant/product/edit/${row.id}`);
    },
    
    // 删除商品
    handleDelete(row) {
      this.$confirm('确认删除该商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取当前商家ID (实际项目中应从登录用户信息或全局状态中获取)
        const merchantId = 1; // 假设当前商家ID为1
        
        deleteProduct(row.id, merchantId)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功');
              this.fetchProducts();
            } else {
              this.$message.error(res.message || '删除失败');
            }
          })
          .catch(err => {
            console.error('删除失败', err);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        // 取消删除操作
      });
    },
    
    // 更新商品状态
    handleStatusChange(row) {
      const statusText = row.status === 1 ? '上架' : '下架';
      
      // 获取当前商家ID (实际项目中应从登录用户信息或全局状态中获取)
      const merchantId = 1; // 假设当前商家ID为1
      
      updateProductStatus(row.id, merchantId, row.status)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(`商品${statusText}成功`);
          } else {
            // 状态更新失败，回滚UI状态
            row.status = row.status === 1 ? 0 : 1;
            this.$message.error(res.message || `商品${statusText}失败`);
          }
        })
        .catch(err => {
          // 状态更新失败，回滚UI状态
          row.status = row.status === 1 ? 0 : 1;
          console.error(`商品${statusText}失败`, err);
          this.$message.error(`商品${statusText}失败`);
        });
    }
  }
}
</script>

<style scoped>
.product-container {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.search-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.status-text {
  font-size: 12px;
  margin-top: 5px;
  color: #666;
}
</style> 